import {Controller, Render, Get, Param, Session, UseBefore, Res } from "routing-controllers";
import { utils } from "../../utils/utils";
import { Service, Inject } from "typedi";
import { InfoServiceImpl } from "../../service/impl/InfoServiceImpl";
import { CarServiceImpl } from "../../service/impl/CarServiceImpl";
import { CheckLoginMiddleware } from "../../middleware/CheckLoginMiddleware";

@Service()
@Controller()
@UseBefore(CheckLoginMiddleware)
export class PlayControllerHome {

	@Inject()
	private infoServiceImpl: InfoServiceImpl;
	
	@Inject()
	private carServiceImpl: CarServiceImpl;
	
	@Get("/coures/play/:couresId/:videoId")
	@Render("home/page/play")
	public async PlayVideo (@Session() session,
	                        @Res() res: any,
	                        @Param("couresId") couresId: string,
	                        @Param("videoId") videoId: string) {
		// 需要播放的课程
		let currentPlayVideo = (await this.infoServiceImpl.getCurrentPlayVideo(videoId))[0];
		
		// 获取课程主体信息
		let courseList = await this.infoServiceImpl.getCourseByObjectId(couresId);
		
		// 获取课程下所属的视频章节
		let courseVideoList = await this.infoServiceImpl.getCourseVideoByObjectId(couresId);

		if (currentPlayVideo == undefined || courseList['code'] == 101) {
			res.redirect('/error')
			return res;
		}else {
			let List = {
				title: utils.titleName(`${currentPlayVideo['courseTitle']}`),
				isShowAction: {
					header: true,
					footer: true
				},
				courseList: courseList,
				courseVideoList: courseVideoList,
				PlayingVideo: currentPlayVideo,
				banner: {
					bannerTitle: currentPlayVideo['courseTitle'],
					bannerUrl: currentPlayVideo['courseVideoImg']
				},
				login: session.user ? session.user : false
			};
			
			// 判断用户将要访问的章节是否收费，如果课程收费，那么课程的章节是否可以试听，如果可以试听直接播放
			// 如果不可以试听那么判断课程是否已经购买，购买了直接播放，没购买加入购物车
			// 如果课程不收费，那么直接播放
			if(courseList['courseCharge'] == '收费') {
				if(currentPlayVideo['courseAudition']) {
					return List
				} else {
					let statusList = await this.carServiceImpl.addCar(session.user.objectId,couresId)
					if(statusList.hasOwnProperty('orderStatus')
						&& statusList['orderStatus'] == 1) {
						return List
					} else {
						res.redirect(`/car`);
						return res;
					}
				}
			} else {
				return List
			}
		}
		

		
	}
}